﻿using BarcodeStandard;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Utils.Draw
{
    public class BarcodeGenerator
    {
        public static byte[] Builder(string code, string label)
        {
            using Barcode barcode = new Barcode();
            // using MemoryStream ms = new MemoryStream();
            barcode.BarWidth = 2;
            barcode.Height = 100;
            barcode.Alignment = AlignmentPositions.Center;
            barcode.IncludeLabel = true;
            barcode.LabelFont.Size = 16;
            barcode.AlternateLabel = label;
            barcode.EncodedType = BarcodeStandard.Type.Code128;
            using var barcodeImage = barcode.Encode(BarcodeStandard.Type.Code128, code);
            //   barcode.SaveImage(ms, SaveTypes.Jpg);

            using SKSurface surface = SKSurface.Create(new SKImageInfo(barcodeImage.Width + 10, barcodeImage.Height + 5));
            surface.Canvas.Clear(SKColor.Parse("#ffffff"));
            surface.Canvas.DrawImage(barcodeImage, 5, 5);
            barcodeImage.Dispose();
            return surface.Snapshot().ToBytes();
        }

        public static void Builder(string fileName, string code, string label)
        {
            using Barcode barcode = new Barcode();
            barcode.BarWidth = 2;
            barcode.Height = 100;
            barcode.Alignment = AlignmentPositions.Center;
            barcode.LabelFont.Size = 16;
            barcode.IncludeLabel = true;
            barcode.AlternateLabel = label;
            using var barcodeImage = barcode.Encode(BarcodeStandard.Type.Code128, code);
            using SKSurface surface = SKSurface.Create(new SKImageInfo(barcodeImage.Width + 10, barcodeImage.Height + 5));
            surface.Canvas.Clear(SKColor.Parse("#ffffff"));
            surface.Canvas.DrawImage(barcodeImage, 5, 5);
            barcodeImage.Dispose();
            using FileStream fileStream = new FileStream(fileName, FileMode.Create);
            surface.Snapshot().ToData(SKEncodedImageFormat.Jpeg, 100).SaveTo(fileStream);
        }
    }
}
